/******************************************************
 *                                                     
 *              Score System               
 *                                                     
 *******************************************************/

/**
 * WebUtility.java
 *
 * 网页前端的一些调用工具函数
 *
 * @author sundy
 * @version 0.0.1
 * lastModified 2011-01-01
 */

package com.sundy.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.sundy.core.Common;
import com.sundy.daosupport.DescriptTblDAO;
import com.sundy.daosupport.RightTblDAO;
import com.sundy.daosupport.ScoreTblDAO;
import com.sundy.daosupport.Subject2descDAO;
import com.sundy.daosupport.SubjectTblDAO;
import com.sundy.service.DescriptTbl;
import com.sundy.service.RightTbl;
import com.sundy.service.ScoreTbl;
import com.sundy.service.StudentTbl;
import com.sundy.service.Subject2desc;
import com.sundy.service.SubjectTbl;
import com.sundy.service.TeacherTbl;

public class WebUtility {
	public static String outSubject(TeacherTbl teacher) {
		SubjectTblDAO dao = SubjectTblDAO
				.getFromApplicationContext(Common.applicationContext);
		List<SubjectTbl> list = dao.findAll();
		StringBuilder sb = new StringBuilder();
		sb.append("<select name='subject'>\n");
		for (SubjectTbl sub : list) {
			if (teacher.getSubject() == sub.getId())
				sb.append("<option selected='selected' value=\"").append(
						sub.getId()).append("\">").append(sub.getCaption())
						.append("</option>\n");
			else
				sb.append("<option value=\"").append(sub.getId()).append("\">")
						.append(sub.getCaption()).append("</option>\n");
		}
		sb.append("</select>\n");
		return sb.toString();
	}

	public static String getSubjectMax(int id) {
		Properties prop = new Properties();
		String path = WebUtility.class.getResource("/").getPath();
		if (path.startsWith("/")) {
			path = path.substring(1) + "config.properties";
		} else
			path = path + "config.properties";
		File file = new File(path);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		FileInputStream inStream = null;
		try {
			inStream = new FileInputStream(path);
			prop.load(inStream);
			return prop.getProperty(String.valueOf(id), "150");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inStream != null)
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return "150";
	}

	public static void setSubjectMax(String id, String max) {
		Properties prop = new Properties();
		String path = WebUtility.class.getResource("/").getPath();
		if (path.startsWith("/")) {
			path = path.substring(1) + "config.properties";
		} else
			path = path + "config.properties";
		File file = new File(path);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		FileInputStream inStream = null;
		FileOutputStream outStream = null;
		try {
			inStream = new FileInputStream(path);
			prop.load(inStream);
			prop.setProperty(id, max);
			outStream = new FileOutputStream(path);
			prop.store(outStream, "");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inStream != null)
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (outStream != null)
				try {
					outStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	public static String outRight(TeacherTbl teacher) {
		StringBuilder sb = new StringBuilder();
		sb.append("<select name='right'>\n");
		if (teacher.getAdmin() == 0) {
			sb.append("<option value='1'>管理员</option>");
			sb.append("<option value='0' selected='selected'>一般用户</option>");
		} else {
			sb.append("<option value='1' selected='selected'>管理员</option>");
			sb.append("<option value='0'>一般用户</option>");
		}
		sb.append("</select>\n");
		return sb.toString();
	}

	public static boolean scoreIt(TeacherTbl user, int subId) {
		RightTblDAO dao = RightTblDAO
				.getFromApplicationContext(Common.applicationContext);
		List<RightTbl> list = dao.findByTeacherId(user.getId());
		for (RightTbl r : list) {
			if (r.getSubjectId().intValue() == subId)
				return true;
		}
		return false;
	}

	private static boolean hasIt(SubjectTbl sub, List<RightTbl> list) {
		for (RightTbl r : list) {
			if (r.getSubjectId().intValue() == sub.getId().intValue())
				return true;
		}
		return false;
	}

	public static String outMapping(TeacherTbl teacher) {
		StringBuilder sb = new StringBuilder();
		RightTblDAO dao = RightTblDAO
				.getFromApplicationContext(Common.applicationContext);
		List<RightTbl> list = dao.findByTeacherId(teacher.getId());
		SubjectTblDAO dao2 = SubjectTblDAO
				.getFromApplicationContext(Common.applicationContext);
		List<SubjectTbl> list2 = dao2.findAll();
		int i = 0;
		sb.append("<table width=\"100%\">\n");
		for (SubjectTbl sub : list2) {
			if (i % 2 == 0)
				sb.append("<tr>\n");
			sb.append("<td>\n");
			if (hasIt(sub, list)) {
				sb.append("<input type=\"checkbox\" name=\"subject\" value=\"")
						.append(sub.getId()).append("\" checked=\"true\"/>")
						.append(sub.getCaption());
			} else
				sb.append("<input type=\"checkbox\" name=\"subject\" value=\"")
						.append(sub.getId()).append("\">").append(
								sub.getCaption());
			sb.append("</td>\n");
			if (i % 2 == 1)
				sb.append("</tr>\n");
			i++;
		}
		if (i % 2 != 1)
			sb.append("</tr>\n");
		sb.append("</table>\n");
		sb.append("<hr size=\"1\" color=\"#cccccc\"/>");
		return sb.toString();
	}

	public static String outDescrpt(DescriptTbl desc) {
		StringBuilder sb = new StringBuilder();
		sb.append("<select name='descript'>\n");
		if (desc.getFinished() == 0) {
			sb.append("<option value='0' selected='selected'>有效</option>");
			sb.append("<option value='1'>已完成</option>");
		} else {
			sb.append("<option value='0'>有效</option>");
			sb.append("<option value='1' selected='selected'>已完成</option>");
		}
		sb.append("</select>\n");
		return sb.toString();
	}

	public static String getRawSubjectCaption(String subject) {
		if (subject.endsWith("-文") || subject.endsWith("-理"))
			return subject.substring(0, subject.length() - 2);
		return subject;
	}

	public static String getNondotString(String inStr) {
		int ipos = inStr.indexOf(".");
		if (ipos == -1)
			return inStr;
		return inStr.substring(0, ipos);
	}

	public static String getStudentScore(StudentTbl student, SubjectTbl subject) {
		ScoreTblDAO dao = ScoreTblDAO
				.getFromApplicationContext(Common.applicationContext);
		ScoreTbl item = dao.finByStudentSubject(student.getId(), subject
				.getId());
		return item == null ? "" : String.valueOf(item.getScore());
	}

	public static void writeScore(int studentId, int subjectId, int score) {
		ScoreTblDAO dao = ScoreTblDAO
				.getFromApplicationContext(Common.applicationContext);
		ScoreTbl item = dao.finByStudentSubject(studentId, subjectId);
		if (item == null) {
			ScoreTbl newItem = new ScoreTbl(studentId, subjectId, score);
			dao.save(newItem);
			dao.getHibernateTemplate().flush();
		} else {
			item.setScore(score);
			dao.merge(item);
			dao.getHibernateTemplate().flush();
		}
	}

	public static String getRefPath(String url) {
		int ipos = url.lastIndexOf("/");
		if (ipos == -1)
			return url;
		return url.substring(0, ipos);
	}

	public static void setFinished(int subjectId, int descId, int finished) {
		Subject2descDAO dao = Subject2descDAO
				.getFromApplicationContext(Common.applicationContext);
		List<Subject2desc> list = dao.findBySubDesc(subjectId, descId);
		if (list == null || list.isEmpty())
			return;
		Subject2desc item = list.get(0);
		item.setFinished(finished);
		dao.merge(item);
		dao.getHibernateTemplate().flush();
	}

	public static List<String> getTeacherSubjects(TeacherTbl teacher) {
		// get subjects
		RightTblDAO daoR = RightTblDAO
				.getFromApplicationContext(Common.applicationContext);
		SubjectTblDAO daoS = SubjectTblDAO
				.getFromApplicationContext(Common.applicationContext);
		DescriptTblDAO daoD = DescriptTblDAO
				.getFromApplicationContext(Common.applicationContext);
		Subject2descDAO daoSD = Subject2descDAO
				.getFromApplicationContext(Common.applicationContext);
		List<RightTbl> listR = daoR.findByTeacherId(teacher.getId());
		List<String> result = new ArrayList<String>();
		for (RightTbl R : listR) {
			SubjectTbl sub = daoS.findById(R.getSubjectId());
			if (sub == null)
				continue;
			Integer subId = sub.getId();
			List<Subject2desc> list = daoSD.findBySubjectId(subId);
			if (list == null || list.isEmpty())
				continue;
			for (Subject2desc item : list) {
				Integer descId = item.getDescId();
				DescriptTbl desc = daoD.findById(descId);
				if (desc == null)
					continue;
				if (desc.getFinished() == 1)
					continue;
				result.add(desc.getCaption() + " " + sub.getCaption() + "|"
						+ descId + "|" + subId);
			}
		}
		return result;
	}
}
